//
//  BulletManager.m
//  MTGraphics
//
//  Created by 莫瑞权 on 2018/7/23.
//  Copyright © 2018年 MT. All rights reserved.
//

#import "TalkFunBulletManager.h"
@interface TalkFunBulletManager()

//表情数组
@property(nonatomic,strong)NSArray *expressionArray;


@property(nonatomic,strong)TalkFunTextLayer *layer;

@property(nonatomic,strong)NSMutableDictionary *layerDict;
@end


@implementation TalkFunBulletManager


- (NSArray *)expressionArray
{
    if(_expressionArray==nil){

        _expressionArray = @[@"[slime]",@"[laugh]",@"[love]",@"[tongue]",@"[daze]",@"[handclap]",@"[titter]",@"[handssors]",@"[six]",@"[heart]",@"[melon]",@"[silly]",@"[dog]",@"[like]",@"[expect]",@"[aha]",@"[hard]",@"[good]",@"[Fireworks]",@"[cool]",@"[why]",@"[pitiful]",@"[amaz]",@"[bye]",@"[666]",@"[flower]",@"[rose]"];
    }
    return _expressionArray;
}


-(NSMutableDictionary *)layerDict
{
    if (_layerDict==nil) {
        _layerDict = [NSMutableDictionary dictionary];
    }
    return _layerDict;
}
- (NSMutableArray*)getexpressionArrayCopy:(NSString*)content
{
   
    NSMutableArray *locationArr = [NSMutableArray new];
    
    for (NSString *tab in self.expressionArray) {
        NSRange range = [content rangeOfString:tab];
           
//           NSInteger point = 0;
           //声明一个临时字符串,记录截取之后的字符串
           NSString * subStr = content;
           while (range.location != NSNotFound) {
//               if (locationArr.count > 0) {
//                   point = range.location + locationArr.count * tab.length;
//               } else {
//                   point = range.location;
//               }
               //记录位置
//               NSNumber *number = [NSNumber numberWithUnsignedInteger:point];
               [locationArr addObject:tab];

               //每次记录之后,把找到的字串截取掉
               subStr = [subStr substringFromIndex:range.location + range.length];
//               NSLog(@"subStr %@",subStr);
               range = [subStr rangeOfString:tab];
//               NSLog(@"rang %@",NSStringFromRange(range));
        }
   
   
      }
    
      return locationArr;
    
}

//图片
//图片绘制的图片
//文字的大小
- (void)Avatar:(UIImage*)image   startingPoint:(CGPoint)point  ntOfSize:(CGFloat)fontSize  with:(TalkFunTextLayer *)layer
{

    
     CGSize   size =  [self contentCellHeightWithText:@"随意" ontOfSize:fontSize];

    CGFloat  hh = 0;
    
    if (fontSize<=20) {
        hh = 5;
    }
    
    //2.画图片
    CALayer *IMageLayer = [self getImageLayer1:image Frame:CGRectMake(- ((size.height+hh)/3.0), 0, size.height+hh , size.height +hh)];
    
    [layer addSublayer:IMageLayer];
}
#pragma mark - containsObject方法
- (NSMutableArray*)removeRepeatWithContainObjFunc:(NSArray *)array {
    NSMutableArray *listArray = [NSMutableArray array];
    
    for (NSString  *str in array) {
        if (![listArray containsObject:str]) {
            [listArray addObject:str];
        }
    }
    
//    NSLog(@"containFunc ====  %@", listArray);
    return listArray;
}
- (TalkFunTextLayer *)withContent:(NSString *)content ontOfSize:(CGFloat)fontSize startingPoint:(CGPoint)point textColor:(UIColor *)Color  Avatar:(UIImage*)image backgroundColor:(UIColor*)
backgroundColor
{
  
    NSMutableDictionary *expressionDict = [self getExpressionDict];
    NSDictionary *expressionDict2 = [self getBigExpressionDict];
    for (int i = 0; i < expressionDict2.count; ++i) {
    //  获取字典中所有的key
     NSArray *keys = [expressionDict2 allKeys];
    //  取出当前位置对应的key
     
     NSString *key = keys[i];
     NSString *value = expressionDict2[key];
        [expressionDict setObject:value forKey:key];

     }
    
    
        //将字符串中" name" 全部替换成 expressionDict[name]
    //   str = [str stringByReplacingOccurrencesOfString :@"name " withString:expressionDict[name]"];
    
    //例如:找到聊天内容的 "[fd]"换成 @"[hard]"
    for (NSString * name in expressionDict) {
        content = [content stringByReplacingOccurrencesOfString:name withString:expressionDict[name]];
    }
    //---------------------------
    TalkFunTextLayer *layer = [[TalkFunTextLayer alloc]init];

    NSString *str = [NSString stringWithFormat:@"%@",content];
    
     //TODO:1.找出所有表情字符
   NSMutableArray *expression = [self getexpressionArrayCopy:content];
    //新的空白
    if (expression.count>0) {
        str = [@"　" stringByAppendingString:content];
    }
   
    
     //TODO:1.删除重复的表情,因为用其中一个, 就能找到所有这个表情的位置
    NSMutableArray *expressionArrayCopy = [self removeRepeatWithContainObjFunc:expression];
    
    NSMutableArray *temp = [NSMutableArray array];
    
    NSString *Space = @"       ";
    //TODO:1.1找出所有表情的位置
   for (int i = 0; i< expressionArrayCopy.count; i++) {
        
    //所有本地表情的名字
     NSString * name = expressionArrayCopy[i];
      
    //找到表情所在的位置
    NSMutableArray *value = [self calculateSubStringCount:content str:name];

    for (NSNumber *inx in value) {
        
        [temp addObject:inx];
        
        //记录表情出现的位置
        [self.layerDict setObject:name forKey:inx];
    }
        //将字符串中"表情" 全部替换成 Space   分层
        str = [str stringByReplacingOccurrencesOfString:name withString:Space];

    }
    //TODO:1.2找到所有表情出现的位置, //升序 ,最前面的表情在inex在0
    //10,
//    20,
//    30,
//    38
    NSArray *result = [temp sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    
//    UIColor * randomColor= [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    
    //TODO:2.msg 内的所有文字
    TalkFunTextLayer *textLayer = [TalkFunTextLayer singleLinePathStandard:str withFont:fontSize withPosition:CGPointMake(point.x, point.y) textColor:Color];
    textLayer.name = @"名字";
    textLayer.backgroundColor = backgroundColor.CGColor;
    
//    textLayer.backgroundColor = randomColor.CGColor;
    layer.contentWidth = [TalkFunTextLayer getTextWidth:str ontOfSize:fontSize].width;
    [layer addSublayer:textLayer];

    //TODO:2.1获取这个字符串ASting中的所有abc的所在的index
    
    //找同表情的所有位置
    NSMutableArray * ar__2 = [self getRangeStr:str findText: Space];
    
    //expressionArrayCopy 删除重复的表情,因为用其中一个, 就能找到所有这个表情的位置
//    if (ar__2.count > expressionArrayCopy.count&&ar__2.count>0) {
//        [ar__2 removeObjectAtIndex:0];
//    }
   
    
  //遍历所有表情位置
//    <__NSArrayI 0x2812db450>(
//    12,
//    19,
//    29
//    )
    for (int i = 0; i< result.count; i++) {
        
      NSNumber *inx = result[i];
        
//      layerDict  {
//            12 = "[slime]";
//            19 = "[handclap]";
//            29 = "[handclap]";
//        }
        //通过位置找出名字
        if (self.layerDict[inx])
        {
            //图片名字
        NSString *imageName = self.layerDict[inx];
        //默认的字符串计算大小
        CGSize size = [self contentCellHeightWithText:content ontOfSize:fontSize];
           
        CGFloat width_1 = 0;
            
        //防止越界
        if(i<ar__2.count && ar__2[i]){
           
            NSNumber *inx_1 = ar__2[i];
            if (str.length > [inx_1 integerValue]) {
            
            //从最前头一直截取到Index
            NSString *name = [str substringToIndex:[inx_1 integerValue]];
            //要把内容与字体 计算size
            CGSize size_1 = [TalkFunTextLayer getTextWidth:name ontOfSize:fontSize];
                  width_1 = size_1.width;

            }

          
        }
       
   //计算一个字的宽度
//    CGSize size_2 = [TalkFunTextLayer getTextWidth:@"1" ontOfSize:fontSize];
            //只要表情字符, 不要[]
         imageName = [imageName stringByReplacingOccurrencesOfString:@"[" withString:@""];
         imageName = [imageName stringByReplacingOccurrencesOfString:@"]" withString:@""];
            
    CGFloat  hh = 0;
    if (fontSize <= 20) {
       hh = 5;
    }
    //有用户头像
    CGFloat imageW = 0;
     if (image) {
//        imageW = size_2.height + hh;
      }
    
    CGRect imageFrame = CGRectMake(width_1 , point.y +((imageW - size.height))/2+10, size.height , size.height);
//    NSLog(@"frame===%@",NSStringFromCGRect(imageFrame));
    //TODO:5. 取出所有的表情的名字  ,通过名字 画表情图片上去
    CALayer *IMageLayer = [self getIMageLayer:imageName Frame:imageFrame];
    [layer addSublayer:IMageLayer];

//    layer.backgroundColor = randomColor.CGColor;
         
        }
      
    }
       
    if (image) {
        //TODO:3.添加默认头像图片绘制
        [self Avatar:image startingPoint:point ntOfSize:fontSize with:textLayer];
    }
    
    return layer;
}
//文字宽度与高度
- (CGSize)contentCellHeightWithText:(NSString*)text ontOfSize:(CGFloat)Font
{
    // 设置字体
    UIFont *font =  [UIFont systemFontOfSize:Font];
    
    //位置
    NSString *name =  [TalkFunTextLayer replaceUnicodeTest:@"随便计算高度用"];
    
    NSDictionary *attrs = @{NSFontAttributeName:font};
    //位置
    CGSize attrsSize = [name sizeWithAttributes:attrs];
    
    return attrsSize;
}
//用图片  绘制图片
- (CALayer*)getImageLayer1:(UIImage *)imageName  Frame:(CGRect)frame
{
    
    CALayer*   myLayer = [CALayer layer];
    // 设置图层的内容
    myLayer.contents = (__bridge id _Nullable)(imageName.CGImage);
    // 设置阴影的颜色
    myLayer.shadowColor = [UIColor clearColor].CGColor;
    // 设置阴影的偏移
    //   myLayer.shadowOffset = CGSizeMake(15, 10);
    // 设置阴影的不透明度
    myLayer.shadowOpacity = 0.6;
    // 设置边角半径
    myLayer.cornerRadius = frame.size.height/2;
 
    // 设置裁剪
    myLayer.masksToBounds = YES;
    // 设置边框线的颜色
    myLayer.borderColor = [UIColor clearColor].CGColor;
    // 设置边框线条的宽度
    //    myLayer.borderWidth = 5.0;
    myLayer.frame = frame;
    myLayer.backgroundColor = [UIColor blackColor].CGColor;
    return myLayer;
}
//用图片名字找到图片  绘制图片
- (CALayer*)getIMageLayer:(NSString *)imageName  Frame:(CGRect)frame
{
    if ([imageName isEqual:@"666"]) {
        imageName = @"six";
    }
    
    CALayer*   myLayer = [CALayer layer];
    // 设置图层的内容
    myLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:imageName].CGImage);
    // 设置阴影的颜色
    myLayer.shadowColor = [UIColor clearColor].CGColor;
    // 设置阴影的偏移
    //   myLayer.shadowOffset = CGSizeMake(15, 10);
    // 设置阴影的不透明度
    myLayer.shadowOpacity = 0.6;
    // 设置边角半径
    //    myLayer.cornerRadius = 15;
    // 设置裁剪
    myLayer.masksToBounds = YES;
    // 设置边框线的颜色
    myLayer.borderColor = [UIColor clearColor].CGColor;
    // 设置边框线条的宽度
    //    myLayer.borderWidth = 5.0;
    myLayer.frame = frame;
    myLayer.backgroundColor = [UIColor clearColor].CGColor;
    return myLayer;
}
/**
 查找子字符串在父字符串中的所有位置
 @param content 父字符串
 @param tab 子字符串
 @return 返回位置数组
 */

- (NSMutableArray*)calculateSubStringCount:(NSString *)content str:(NSString *)tab {
    int location = 0;
    NSMutableArray *locationArr = [NSMutableArray new];
    NSRange range = [content rangeOfString:tab];
    if (range.location == NSNotFound){
        return locationArr;
    }
    //声明一个临时字符串,记录截取之后的字符串
    NSString * subStr = content;
    while (range.location != NSNotFound) {
        if (location == 0) {
            location += range.location;
        } else {
            location += range.location + tab.length;
        }
        //记录位置
        NSNumber *number = [NSNumber numberWithUnsignedInteger:location];
        [locationArr addObject:number];
        //每次记录之后,把找到的字串截取掉
        subStr = [subStr substringFromIndex:range.location + range.length];
        NSLog(@"subStr %@",subStr);
        range = [subStr rangeOfString:tab];
        NSLog(@"rang %@",NSStringFromRange(range));
    }
    return locationArr;
}
#pragma mark - 获取这个字符串ASting中的所有abc的所在的index
- (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText
{
    
    NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:3];
    
    if (findText == nil && [findText isEqualToString:@""])
    {
        
        return nil;
        
    }
    
    NSRange rang = [text rangeOfString:findText]; //获取第一次出现的range
    
    if (rang.location != NSNotFound && rang.length != 0)
    {
        
        [arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//将第一次的加入到数组中
        
        NSRange rang1 = {0,0};
        
        NSInteger location = 0;
        
        NSInteger length = 0;
        
        for (int i = 0;; i++)
        {
            
            if (0 == i)
            {
                
                //去掉这个abc字符串
                location = rang.location + rang.length;
                
                length = text.length - rang.location - rang.length;
                
                rang1 = NSMakeRange(location, length);
                
            }
            else
            {
                
                location = rang1.location + rang1.length;
                
                length = text.length - rang1.location - rang1.length;
                
                rang1 = NSMakeRange(location, length);
                
            }
            
            //在一个range范围内查找另一个字符串的range
            
            rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
            
            if (rang1.location == NSNotFound && rang1.length == 0)
            {
                
                break;
                
            }
            else//添加符合条件的location进数组
                
            [arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
            
        }
        
        return arrayRanges;
        
    }
    
    return nil;
    
}

-(NSMutableDictionary*)getExpressionDict
{

//    NSMutableArray *array = [self getArray];
//
//    for (int  i = 16; i<35; i++) {
//
//        [array addObject:[NSString stringWithFormat:@"[emoticon%i]",i+1]];
//
//    }

    NSDictionary *expressionDict1 = @{@"[fd]":@"[hard]",
                                     @"[lg]":@"[aha]",
                                     @"[qu]":@"[why]",
                                     @"[fl]":@"[Fireworks]",
                                     @"[kl]":@"[pitiful]",
                                     @"[jy]":@"[amaz]",
                                     @"[gz]":@"[good]",
                                     @"[hx]":@"[cool]",
                                     @"[tx]":@"[love]",
                                     @"[ag]":@"[bye]",
                                     @"[S_FLOWER]":@"[rose]"};
    
    
    NSMutableDictionary *expressionDict = [NSMutableDictionary dictionaryWithDictionary:expressionDict1];
    
    return expressionDict;
}

-(NSDictionary*)getBigExpressionDict

{
    return @{@"[slime]":@"[slime]",
             @"[laugh]":@"[laugh]",
             @"[love]":@"[love]",
             @"[tongue]":@"[tongue]",
             @"[daze]":@"[daze]",
             @"[handclap]":@"[handclap]",
             @"[titter]":@"[titter]",
             @"[handssors]":@"[handssors]",
             @"[six]":@"[six]",
             @"[heart]":@"[heart]",
             @"[melon]":@"[melon]",
             @"[silly]":@"[silly]",
             @"[dog]":@"[dog]",
             @"[like]":@"[like]",
             @"[expect]":@"[expect]",
             @"[flower]":@"[flower]",
             @"[色]":@"[emoticon17]",
             @"[调皮]":@"[emoticon18]",
             @"[害羞]":@"[emoticon19]",
             @"[奸笑]":@"[emoticon20]",
             @"[尴尬]":@"[emoticon21]",
             @"[惊讶]":@"[emoticon22]",
             @"[闭嘴]":@"[emoticon23]",
             @"[呲牙]":@"[emoticon24]",
             @"[大哭]":@"[emoticon25]",
            
             @"[囧]":@"[emoticon26]",
             @"[难过]":@"[emoticon27]",
             @"[敲打]":@"[emoticon28]",
             @"[委屈]":@"[emoticon29]",
             @"[疑问]":@"[emoticon30]",
             @"[郁闷]":@"[emoticon31]",
             @"[再见]":@"[emoticon32]",
             @"[可怜]":@"[emoticon33]",
             @"[捂脸]":@"[emoticon34]",
             @"[笑哭]":@"[emoticon35]",
             @"[安慰]":@"[emoticon26]",
             @"[666]":@"[six]",
};
}
@end
